package ilender.util;

import java.util.List;
import java.util.ArrayList;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.impl.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.commons.io.IOUtils;
import com.google.gson.*;

/**
 * Tools for handling HTTP requests.
 */
public final class HttpTools{
	/*Instantiation Guard*/private HttpTools(){}

	/**Performs a GET request.*/
	public static String requestGet(String url){
		try{
			HttpResponse response=new DefaultHttpClient().execute(new HttpGet(url));
			HttpEntity entity=response.getEntity();
			if(null!=entity){
				InputStream stream=entity.getContent();
				try{
					return IOUtils.toString(stream);
				}finally{
					stream.close();
				}
			}
			throw new RuntimeException(String.format("Got nothing from %s",url));
		}catch(IOException e){throw new RuntimeException(e);}
	}

	/**Performs a GET request, parsing the result as JSON.*/
	public static JsonElement requestGetJson(String url){
		try{
			HttpResponse response=new DefaultHttpClient().execute(new HttpGet(url));
			HttpEntity entity=response.getEntity();
			if(null!=entity){
				InputStream stream=entity.getContent();
				try{
					return new JsonParser().parse(new InputStreamReader(stream));
				}finally{
					stream.close();
				}
			}
			throw new RuntimeException(String.format("Got nothing from %s",url));
		}catch(IOException e){throw new RuntimeException(e);}
	}

	/**
	 * Performs a POST request, parsing the result as JSON.
	 *
	 * @param url The request url.
	 * @param fields The POST fields.
	 */
	public static JsonElement requestPostJson(String url,String... fields){
		try{
			HttpPost httpPost=new HttpPost(url);
			List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
			for(int i=0;i<fields.length;i+=2)
				nameValuePairs.add(new BasicNameValuePair(fields[i],fields[i+1]));
			//System.out.println(url);
			//System.out.println(IOUtils.toString(new UrlEncodedFormEntity(nameValuePairs).getContent()));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response=new DefaultHttpClient().execute(httpPost);
			HttpEntity entity=response.getEntity();
			if(null!=entity){
				InputStream stream=entity.getContent();
				try{
					return new JsonParser().parse(new InputStreamReader(stream));
				}finally{
					stream.close();
				}
			}
			throw new RuntimeException(String.format("Got nothing from %s",url));
		}catch(IOException e){throw new RuntimeException(e);}
	}
}
